// 通用工具函数
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const moment = require('moment');

// 密码加密
const hashPassword = async (password) => {
  const saltRounds = parseInt(process.env.BCRYPT_ROUNDS) || 10;
  return await bcrypt.hash(password, saltRounds);
};

// 密码验证
const comparePassword = async (password, hashedPassword) => {
  return await bcrypt.compare(password, hashedPassword);
};

// 生成JWT Token
const generateToken = (userId, role = 'user') => {
  return jwt.sign(
    { userId, role },
    process.env.JWT_SECRET,
    { expiresIn: process.env.JWT_EXPIRES_IN || '7d' }
  );
};

// 验证JWT Token
const verifyToken = (token) => {
  return jwt.verify(token, process.env.JWT_SECRET);
};

// 格式化日期时间
const formatDateTime = (date, format = 'YYYY-MM-DD HH:mm:ss') => {
  return moment(date).format(format);
};

// 计算时间差（小时）
const calculateHours = (startTime, endTime) => {
  const start = moment(startTime);
  const end = moment(endTime);
  return end.diff(start, 'hours', true);
};

// 生成订单号
const generateOrderNumber = () => {
  const timestamp = Date.now();
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
  return `ORD${timestamp}${random}`;
};

// 生成随机字符串
const generateRandomString = (length = 8) => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
};

// 验证手机号
const isValidPhone = (phone) => {
  const phoneRegex = /^1[3-9]\d{9}$/;
  return phoneRegex.test(phone);
};

// 验证邮箱
const isValidEmail = (email) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
};

// 分页计算
const calculatePagination = (page = 1, pageSize = 10) => {
  const currentPage = Math.max(1, parseInt(page));
  const size = Math.min(100, Math.max(1, parseInt(pageSize)));
  const offset = (currentPage - 1) * size;
  
  return {
    page: currentPage,
    pageSize: size,
    offset,
    limit: size
  };
};

// 格式化金额（保留两位小数）
const formatAmount = (amount) => {
  return parseFloat(amount).toFixed(2);
};

// 安全的JSON解析
const safeJsonParse = (str, defaultValue = null) => {
  try {
    return JSON.parse(str);
  } catch (error) {
    return defaultValue;
  }
};

// 移除对象中的空值
const removeEmptyValues = (obj) => {
  const result = {};
  for (const [key, value] of Object.entries(obj)) {
    if (value !== null && value !== undefined && value !== '') {
      result[key] = value;
    }
  }
  return result;
};

// 深度克隆对象
const deepClone = (obj) => {
  return JSON.parse(JSON.stringify(obj));
};

// 延迟函数
const delay = (ms) => {
  return new Promise(resolve => setTimeout(resolve, ms));
};

// 重试函数
const retry = async (fn, maxRetries = 3, delayMs = 1000) => {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      await delay(delayMs);
    }
  }
};

module.exports = {
  hashPassword,
  comparePassword,
  generateToken,
  verifyToken,
  formatDateTime,
  calculateHours,
  generateOrderNumber,
  generateRandomString,
  isValidPhone,
  isValidEmail,
  calculatePagination,
  formatAmount,
  safeJsonParse,
  removeEmptyValues,
  deepClone,
  delay,
  retry
};
